import { useState, useCallback, useMemo } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import type {
  PaginationParams,
  SearchParams,
  SortParams,
  PaginationResponse,
  ApiResponse
} from '@/types/common';

// 表格配置类型
export interface TableConfig<T = unknown> {
  // 基础配置
  queryKey: string;
  fetchData: (params: TableFetchParams) => Promise<PaginationResponse<T>>;

  // 分页配置
  defaultPageSize?: number;
  showPagination?: boolean;
  pageSizeOptions?: string[];

  // 搜索配置
  searchFields?: TableSearchField[];
  enableSearch?: boolean;

  // 排序配置
  defaultSort?: SortParams;
  enableSort?: boolean;

  // 树形配置
  isTree?: boolean;
  treeDataKey?: string;
  expandable?: boolean;

  // 回调函数
  onSuccess?: (data: PaginationResponse<T>) => void;
  onError?: (error: Error) => void;

  // 其他配置
  enableExport?: boolean;
  enableDelete?: boolean;
  rowSelection?: boolean;
}

// 搜索字段配置
export interface TableSearchField {
  key: string;
  label: string;
  type: 'input' | 'select' | 'date' | 'number' | 'switch';
  placeholder?: string;
  options?: Array<{ label: string; value: unknown }>;
  rules?: unknown[];
}

// 表格获取参数
export interface TableFetchParams extends PaginationParams {
  search?: SearchParams;
  sort?: SortParams;
}

// 表格返回值
export interface TableReturn<T = unknown> {
  // 数据相关
  data: T[];
  total: number;
  loading: boolean;
  error: Error | null;

  // 分页相关
  pagination: {
    current: number;
    pageSize: number;
    total: number;
    showSizeChanger: boolean;
    showQuickJumper: boolean;
    showTotal: (total: number, range: [number, number]) => string;
    pageSizeOptions: string[];
  };

  // 搜索相关
  searchParams: SearchParams;
  searchFields: TableSearchField[];
  handleSearch: (params: SearchParams) => void;
  handleResetSearch: () => void;

  // 排序相关
  sortParams: SortParams | null;
  handleSort: (sorter: { field: string; order: 'ascend' | 'descend' | null }) => void;

  // 表格变化处理
  handleTableChange: (
    pagination: { current: number; pageSize: number },
    filters: Record<string, unknown[]>,
    sorter: { field: string; order: 'ascend' | 'descend' | null }
  ) => void;

  // 其他功能
  refresh: () => void;
  exportData: (format: 'csv' | 'excel' | 'pdf') => Promise<void>;
  handleDelete: (ids: (string | number)[]) => void;
  deleteLoading: boolean;

  // 树形相关
  expandedRowKeys: (string | number)[];
  handleExpand: (expanded: boolean, record: T) => void;
  handleExpandedRowsChange: (keys: (string | number)[]) => void;
}

// 统一的表格 hook
export function useBaseTable<T extends Record<string, unknown> = Record<string, unknown>>(
  config: TableConfig<T>
): TableReturn<T> {
  const {
    queryKey,
    fetchData,
    defaultPageSize = 10,
    showPagination = true,
    pageSizeOptions = ['10', '20', '50', '100'],
    searchFields = [],
    enableSearch = true,
    defaultSort,
    enableSort = true,
    isTree = false,
    expandable = false,
    onSuccess,
    onError,
    enableExport = false,
    enableDelete = false,
    rowSelection = false,
  } = config;

  // 分页状态
  const [paginationState, setPaginationState] = useState({
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
  });

  // 搜索状态
  const [searchParams, setSearchParams] = useState<SearchParams>({});

  // 排序状态
  const [sortParams, setSortParams] = useState<SortParams | null>(defaultSort || null);

  // 树形展开状态
  const [expandedRowKeys, setExpandedRowKeys] = useState<(string | number)[]>([]);

  // 生成查询键
  const queryKeyArray = useMemo(() => [
    queryKey,
    paginationState.current,
    paginationState.pageSize,
    JSON.stringify(searchParams),
    JSON.stringify(sortParams),
  ], [queryKey, paginationState.current, paginationState.pageSize, searchParams, sortParams]);

  // 数据获取
  const {
    data: responseData,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: queryKeyArray,
    queryFn: async () => {
      const params: TableFetchParams = {
        page: paginationState.current,
        pageSize: paginationState.pageSize,
        search: Object.keys(searchParams).length > 0 ? searchParams : undefined,
        sort: sortParams,
      };

      try {
        const response = await fetchData(params);
        // 更新总数
        setPaginationState(prev => ({
          ...prev,
          total: response.total,
        }));
        onSuccess?.(response);
        return response;
      } catch (err) {
        const error = err as Error;
        onError?.(error);
        throw error;
      }
    },
    enabled: true,
    placeholderData: (previousData) => previousData,
  });

  // 处理分页变化
  const handlePaginationChange = useCallback((current: number, pageSize: number) => {
    setPaginationState(prev => ({
      ...prev,
      current,
      pageSize,
    }));
  }, []);

  // 分页配置
  const pagination = useMemo(() => ({
    current: paginationState.current,
    pageSize: paginationState.pageSize,
    total: paginationState.total,
    showSizeChanger: showPagination,
    showQuickJumper: showPagination,
    showTotal: (total: number, range: [number, number]) =>
      `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions,
  }), [paginationState, showPagination, pageSizeOptions]);

  // 处理搜索
  const handleSearch = useCallback((params: SearchParams) => {
    setSearchParams(params);
    setPaginationState(prev => ({
      ...prev,
      current: 1, // 搜索时重置到第一页
    }));
  }, []);

  // 重置搜索
  const handleResetSearch = useCallback(() => {
    setSearchParams({});
    setPaginationState(prev => ({
      ...prev,
      current: 1,
    }));
  }, []);

  // 处理排序
  const handleSort = useCallback((sorter: { field: string; order: 'ascend' | 'descend' | null }) => {
    if (sorter.field && sorter.order) {
      setSortParams({
        field: sorter.field,
        order: sorter.order === 'ascend' ? 'asc' : 'desc',
      });
    } else {
      setSortParams(null);
    }
  }, []);

  // 处理过滤
  const handleFilter = useCallback((filters: Record<string, unknown[]>) => {
    const filterParams: SearchParams = {};
    Object.keys(filters).forEach(key => {
      if (filters[key] && filters[key].length > 0) {
        filterParams[key] = filters[key];
      }
    });
    setSearchParams(prev => ({
      ...prev,
      ...filterParams,
    }));
    setPaginationState(prev => ({
      ...prev,
      current: 1,
    }));
  }, []);

  // 处理表格变化
  const handleTableChange = useCallback((
    pagination: { current: number; pageSize: number },
    filters: Record<string, unknown[]>,
    sorter: { field: string; order: 'ascend' | 'descend' | null }
  ) => {
    handlePaginationChange(pagination.current, pagination.pageSize);
    handleFilter(filters);
    handleSort(sorter);
  }, [handlePaginationChange, handleFilter, handleSort]);

  // 刷新数据
  const refresh = useCallback(() => {
    refetch();
  }, [refetch]);

  // 导出数据
  const exportData = useCallback(async (format: 'csv' | 'excel' | 'pdf') => {
    if (!enableExport) return;

    try {
      // TODO: 实现导出功能
      console.log(`Exporting data as ${format}`, {
        data: responseData?.data || [],
        searchParams,
        sortParams,
      });
    } catch (error) {
      console.error('Export failed:', error);
    }
  }, [enableExport, responseData?.data, searchParams, sortParams]);

  // 删除 mutation
  const deleteMutation = useMutation({
    mutationFn: async (ids: (string | number)[]) => {
      if (!enableDelete) return;
      // TODO: 调用实际的删除 API
      console.log('Deleting items:', ids);
      return Promise.resolve();
    },
    onSuccess: () => {
      refresh();
    },
  });

  // 处理删除
  const handleDelete = useCallback((ids: (string | number)[]) => {
    if (!enableDelete) return;
    deleteMutation.mutate(ids);
  }, [enableDelete, deleteMutation]);

  // 处理展开
  const handleExpand = useCallback((expanded: boolean, record: T) => {
    if (!expandable) return;

    const recordId = (record as any).id;
    setExpandedRowKeys(prev => {
      if (expanded) {
        return [...prev, recordId];
      } else {
        return prev.filter(key => key !== recordId);
      }
    });
  }, [expandable]);

  // 处理展开行变化
  const handleExpandedRowsChange = useCallback((keys: (string | number)[]) => {
    if (!expandable) return;
    setExpandedRowKeys(keys);
  }, [expandable]);

  return {
    // 数据相关
    data: responseData?.data || [],
    total: responseData?.total || 0,
    loading: isLoading,
    error: error as Error | null,

    // 分页相关
    pagination,

    // 搜索相关
    searchParams,
    searchFields: enableSearch ? searchFields : [],
    handleSearch,
    handleResetSearch,

    // 排序相关
    sortParams,
    handleSort,

    // 表格变化处理
    handleTableChange,

    // 其他功能
    refresh,
    exportData,
    handleDelete,
    deleteLoading: deleteMutation.isLoading,

    // 树形相关
    expandedRowKeys,
    handleExpand,
    handleExpandedRowsChange,
  };
}

// 便捷的创建表格配置的函数
export function createTableConfig<T = unknown>(
  baseConfig: Omit<TableConfig<T>, 'fetchData'>
): (fetchData: (params: TableFetchParams) => Promise<PaginationResponse<T>>) => TableConfig<T> {
  return (fetchData) => ({
    ...baseConfig,
    fetchData,
  });
}